package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.wemedia.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @package com.heima.user.service.impl
 * @Date 2022/3/7
 * @project heima-leadnews
 */
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDTO dto) {

        //判断是否携带手机号和密码
        if (StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"账户不存在");
            }
            String inputPsw = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (!inputPsw.equals(apUser.getPassword())){
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            apUser.setPassword("");
            apUser.setPhone("");
            apUser.setSalt("");
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }
        else {
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
